package com.tc.activiti.base.web;


import com.tc.activiti.base.entity.APIPageList;
import com.tc.activiti.base.entity.APIPageResult;
import com.tc.activiti.base.entity.PageList;
import com.tc.activiti.base.entity.PageResult;
import jodd.util.StringPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author zengqingfa
 * @date 2019/10/21 17:35
 * @description
 * @email zengqingfa_java@163.com
 */
public class GenericController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MultipartResolver multipartResolver;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    protected MultipartResolver getMultipartResolver() {
        return multipartResolver;
    }

    protected HttpServletRequest getRequest() {
        try {
            request.setCharacterEncoding(StringPool.UTF_8);
        } catch (UnsupportedEncodingException ignore) {
        }
        return request;
    }

    protected HttpServletResponse getResponse() {
        response.setCharacterEncoding(StringPool.UTF_8);
        return response;
    }

    /**
     * 构建分页列表数据
     *
     * @param data
     * @return
     */
    protected <E> APIPageList<E> getAPIPageList(List<E> data) {
        APIPageList<E> apiPageList = new APIPageList<E>();

        apiPageList.setDataResult(data);
        if (null != data && data instanceof PageList) {
            PageList<E> pageList = (PageList<E>) data;
            PageResult pageResult = pageList.getPageResult() != null ? pageList.getPageResult() : new PageResult();
            APIPageResult apiPageResult = new APIPageResult();
            apiPageResult.setPage(pageResult.getPage());
            apiPageResult.setLimit(pageResult.getLimit());
            apiPageResult.setTotalCount(pageResult.getTotalCount());
            apiPageList.setPageResult(apiPageResult);
        }

        return apiPageList;
    }
}
